package com.game.service.comm;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 增强版指令重复发送判断器
 * 支持按用户隔离的指令重复检测
 */
public class AdvancedCommandDuplicateChecker {

    // 按用户分组的指令缓存：userId -> (command -> timestamp)
    private final Map<String, Map<String, Long>> userCommandCache;
    private final long duplicateInterval;

    public AdvancedCommandDuplicateChecker() {
        this(3000);
    }

    public AdvancedCommandDuplicateChecker(long duplicateInterval) {
        this.userCommandCache = new ConcurrentHashMap<>();
        this.duplicateInterval = duplicateInterval;
    }

    /**
     * 检查指定用户的指令是否重复
     * @param userId 用户ID
     * @param command 指令内容
     * @return true-重复指令, false-新指令
     */
    public boolean isDuplicate(String userId, String command) {
        if (userId == null || command == null) {
            return false;
        }

        long currentTime = System.currentTimeMillis();
        String trimmedCommand = command.trim();

        // 获取用户的指令缓存
        Map<String, Long> commandCache = userCommandCache.computeIfAbsent(
                userId, k -> new ConcurrentHashMap<>()
        );

        synchronized (commandCache) {
            Long lastTime = commandCache.get(trimmedCommand);

            if (lastTime == null) {
                // 第一次收到该指令
                commandCache.put(trimmedCommand, currentTime);
                return false;
            } else {
                if (currentTime - lastTime <= duplicateInterval) {
                    // 3秒内重复，更新时间戳
                    commandCache.put(trimmedCommand, currentTime);
                    return true;
                } else {
                    // 超过3秒，不算重复，更新时间戳
                    commandCache.put(trimmedCommand, currentTime);
                    return false;
                }
            }
        }
    }

    /**
     * 清理所有用户的过期缓存
     */
    public void cleanup() {
        long currentTime = System.currentTimeMillis();

        userCommandCache.forEach((userId, commandCache) -> {
            synchronized (commandCache) {
                commandCache.entrySet().removeIf(entry ->
                        currentTime - entry.getValue() > duplicateInterval * 2
                );
            }
        });

        // 清理空的用户缓存
        userCommandCache.entrySet().removeIf(entry ->
                entry.getValue().isEmpty()
        );
    }

    /**
     * 清理指定用户的缓存
     */
    public void cleanupUser(String userId) {
        if (userId != null) {
            userCommandCache.remove(userId);
        }
    }

    /**
     * 获取用户数量
     */
    public int getUserCount() {
        return userCommandCache.size();
    }

    /**
     * 清空所有缓存
     */
    public void clear() {
        userCommandCache.clear();
    }
}